<template>
  <view class="uni-container">
    <uni-forms ref="form" :model="formData" validateTrigger="bind">
      <uni-forms-item name="goods_id" label="商品ID">
        <uni-easyinput placeholder="商品ID,如'goods_id': 57442" type="number" v-model="formData.goods_id"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="cat_id" label="父级ID">
        <uni-easyinput placeholder="父级ID" type="number" v-model="formData.cat_id"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="goods_name" label="商品名称">
        <uni-easyinput placeholder="商品名称，如：创维彩电40G6A" v-model="formData.goods_name" trim="both"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="goods_price" label="商品价格">
        <uni-easyinput placeholder="商品价格，如：2999" type="number" v-model="formData.goods_price"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="goods_number" label="商品数量">
        <uni-easyinput placeholder="商品数量，如：100" type="number" v-model="formData.goods_number"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="goods_weight" label="商品重量">
        <uni-easyinput placeholder="商品重量，如：50" type="number" v-model="formData.goods_weight"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="goods_introduce" label="商品介绍">
        <div id="div1">
			<div v-html="formData.goods_introduce"></div>
		</div>
      </uni-forms-item>
      <uni-forms-item name="goods_picture" label="商品图片">
        <uni-file-picker return-type="object" v-model="formData.goods_picture"></uni-file-picker>
      </uni-forms-item>
      <uni-forms-item name="goods_small_logo" label="商品图片URL">
        <uni-easyinput placeholder="商品图片URL，如：http://image2.suning...jpg" v-model="formData.goods_small_logo"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="parent_id" label="parent_id">
        <uni-easyinput placeholder="父ID，用于多级分类" v-model="formData.parent_id" trim="both"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="cat_one_id" label="一级分类ID">
        <uni-easyinput placeholder="一级分类ID" type="number" v-model="formData.cat_one_id"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="cat_two_id" label="二级分类ID">
        <uni-easyinput placeholder="二级分类ID" type="number" v-model="formData.cat_two_id"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="cat_three_id" label="三级分类ID">
        <uni-easyinput placeholder="三级分类ID" type="number" v-model="formData.cat_three_id"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="orderId" label="排序">
        <uni-easyinput placeholder="数字小的排前面" type="number" v-model="formData.orderId"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="state" label="是否显示">
        <switch @change="binddata('state', $event.detail.value)" :checked="formData.state"></switch>
      </uni-forms-item>
      <view class="uni-button-group">
        <button type="primary" class="uni-button" style="width: 100px;" @click="submit">提交</button>
        <navigator open-type="navigateBack" style="margin-left: 15px;">
          <button class="uni-button" style="width: 100px;">返回</button>
        </navigator>
      </view>
    </uni-forms>
  </view>
</template>

<script>
  import { validator } from '../../js_sdk/validator/shop_goodsDetail.js';
  import E from 'wangeditor'

  const db = uniCloud.database();
  const dbCmd = db.command;
  const dbCollectionName = 'shop_goodsDetail';
  let editor = null;

  function getValidator(fields) {
    let result = {}
    for (let key in validator) {
      if (fields.includes(key)) {
        result[key] = validator[key]
      }
    }
    return result
  }

  

  export default {
    data() {
      let formData = {
        "goods_id": null,
        "cat_id": null,
        "goods_name": "",
        "goods_price": null,
        "goods_number": null,
        "goods_weight": null,
        "goods_introduce": "",
        "goods_picture": null,
        "goods_small_logo": "",
        "parent_id": "",
        "cat_one_id": null,
        "cat_two_id": null,
        "cat_three_id": null,
        "orderId": 100,
        "state": true
      }
      return {
        formData,
        formOptions: {},
        rules: {
          ...getValidator(Object.keys(formData))
        }
      }
    },
    onLoad(e) {
      if (e.id) {
        const id = e.id
        this.formDataId = id
        this.getDetail(id)
      }
    },
    onReady() {
      this.$refs.form.setRules(this.rules)
	  this.onWangEdit()
    },
    methods: {
      //初始化WangEdit
      onWangEdit(){
      		  editor = new E('#div1')
      		  editor.config.zIndex = 0		//修改编辑器的层级，不让它盖住系统提示
      		  editor.config.onblur =  (newHtml) =>{
      		     		  //console.log('onblur', newHtml) // 获取最新的 html 内容
      					  this.formData.goods_introduce = newHtml  //将内容赋值到需要的字段
      		  			}
      		  
      		  //在编辑器里插入图片,调用该函数可以在编辑器中增加“上传图片”功能，上传完成后可以获得resultFiles（上传的数组文件）和insertImgFn方法，通过insertImgFn(imgUrl)可以把图片插入到编辑器中
      		  editor.config.customUploadImg = function (resultFiles, insertImgFn) {		
      		  		//console.log(resultFiles)
      				//把传到编辑器里的图片上传到我们自己的云端，见：https://doc.dcloud.net.cn/uniCloud/storage/dev.html#uploadfile
      				//uniCloud.uploadFile({filePath: filePath,cloudPath: 'a.jpg' );
      				//这里需要把resultFiles文件里的数据转变成上面函数里的两个参数
      				resultFiles.forEach(item=>{
      					let path = URL.createObjectURL(item)	//将file格式转变成blob格式
      					let name = item.name
      					uniCloud.uploadFile({
      						filePath:path,
      						cloudPath:name
      					}).then(res=>{				//上传后返回的res.fileID就是我们的图片的网址
      						insertImgFn(res.fileID)
      					})
      				})
      		  }
      		  editor.create()
      },
	  
      /**
       * 验证表单并提交
       */
      submit() {
        uni.showLoading({
          mask: true
        })
        this.$refs.form.validate().then((res) => {
          return this.submitForm(res)
        }).catch(() => {
        }).finally(() => {
          uni.hideLoading()
        })
      },

      /**
       * 提交表单
       */
      submitForm(value) {
		//防止富文件编辑器内容未赋值就直接提交，这里再一次赋值
		value.goods_introduce = editor.txt.html()  
        // 使用 clientDB 提交数据
        return db.collection(dbCollectionName).doc(this.formDataId).update(value).then((res) => {
          uni.showToast({
            title: '修改成功'
          })
          this.getOpenerEventChannel().emit('refreshData')
          setTimeout(() => uni.navigateBack(), 500)
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        })
      },

      /**
       * 获取表单数据
       * @param {Object} id
       */
      getDetail(id) {
        uni.showLoading({
          mask: true
        })
        db.collection(dbCollectionName).doc(id).field("goods_id,cat_id,goods_name,goods_price,goods_number,goods_weight,goods_introduce,goods_picture,goods_small_logo,parent_id,cat_one_id,cat_two_id,cat_three_id,orderId,state").get().then((res) => {
          const data = res.result.data[0]
          if (data) {
            this.formData = data
            
          }
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        }).finally(() => {
          uni.hideLoading()
        })
      }
    }
  }
</script>
